import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:online_bookstore/models/book.dart';
import 'package:online_bookstore/services/api_service.dart';

// API Service Provider
final apiServiceProvider = Provider<ApiService>((ref) {
  final apiService = ApiService();
  apiService.initialize();
  return apiService;
});

// Books State
class BooksState {
  final List<Book> books;
  final bool isLoading;
  final String? error;
  final bool hasMore;
  final int currentPage;

  const BooksState({
    this.books = const [],
    this.isLoading = false,
    this.error,
    this.hasMore = true,
    this.currentPage = 1,
  });

  BooksState copyWith({
    List<Book>? books,
    bool? isLoading,
    String? error,
    bool? hasMore,
    int? currentPage,
  }) {
    return BooksState(
      books: books ?? this.books,
      isLoading: isLoading ?? this.isLoading,
      error: error ?? this.error,
      hasMore: hasMore ?? this.hasMore,
      currentPage: currentPage ?? this.currentPage,
    );
  }
}

// Books Notifier
class BooksNotifier extends StateNotifier<BooksState> {
  final ApiService _apiService;

  BooksNotifier(this._apiService) : super(const BooksState());

  Future<void> loadBooks({
    String? category,
    String? search,
    String? sortBy,
    String? sortOrder = 'asc',
    bool refresh = false,
  }) async {
    if (refresh) {
      state = const BooksState();
    }

    if (state.isLoading) return;

    state = state.copyWith(isLoading: true, error: null);

    try {
      final newBooks = await _apiService.getBooks(
        page: state.currentPage,
        category: category,
        search: search,
        sortBy: sortBy,
        sortOrder: sortOrder,
      );

      state = state.copyWith(
        books: refresh ? newBooks : [...state.books, ...newBooks],
        isLoading: false,
        hasMore: newBooks.length >= 20, // Assuming 20 is page size
        currentPage: state.currentPage + 1,
      );
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: e.toString(),
      );
    }
  }

  Future<void> refreshBooks({
    String? category,
    String? search,
    String? sortBy,
    String? sortOrder = 'asc',
  }) async {
    await loadBooks(
      category: category,
      search: search,
      sortBy: sortBy,
      sortOrder: sortOrder,
      refresh: true,
    );
  }

  void clearError() {
    state = state.copyWith(error: null);
  }
}

// Books Provider
final booksProvider = StateNotifierProvider<BooksNotifier, BooksState>((ref) {
  final apiService = ref.watch(apiServiceProvider);
  return BooksNotifier(apiService);
});

// Featured Books Provider
final featuredBooksProvider = FutureProvider<List<Book>>((ref) async {
  final apiService = ref.watch(apiServiceProvider);
  return await apiService.getFeaturedBooks();
});

// Categories Provider
final categoriesProvider = FutureProvider<List<String>>((ref) async {
  final apiService = ref.watch(apiServiceProvider);
  return await apiService.getCategories();
});

// Book Detail Provider
final bookDetailProvider = FutureProvider.family<Book, String>((ref, bookId) async {
  final apiService = ref.watch(apiServiceProvider);
  return await apiService.getBookById(bookId);
});

// Books by Category Provider
final booksByCategoryProvider = FutureProvider.family<List<Book>, String>((ref, category) async {
  final apiService = ref.watch(apiServiceProvider);
  return await apiService.getBooksByCategory(category);
});
